package alchemist.persistence;

import java.util.HashSet;
import java.util.Set;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import org.springframework.stereotype.Repository;

import alchemist.dao.ProgressDao;
import alchemist.model.Element;
import alchemist.model.Progress;

@Repository
public class JdoProgressDao implements ProgressDao
{

    @Override
    public void save( String userId, Set< Element > results )
    {
        final Set< String > elementIds = new HashSet< String >();
        for ( Element element : results )
        {
            elementIds.add( element.getId() );
        }
        final PersistenceManager pm = PMF.getManager();
        Progress progress = null;
        try
        {
            progress = pm.getObjectById( Progress.class, userId );
            progress.addDiscovered( elementIds );
            pm.makePersistent( progress );
        }
        catch ( JDOObjectNotFoundException e )
        {
            progress = new Progress();
            progress.setUserId( userId );
            progress.addDiscovered( elementIds );
            pm.makePersistent( progress );
        }
        finally
        {
            pm.close();
        }
    }

    @Override
    public Set< String > retrieveIds( String userId )
    {
        Set< String > result = new HashSet< String >();
        final PersistenceManager pm = PMF.getManager();
        try
        {
            Progress progress = pm.getObjectById( Progress.class, userId );
            if ( progress != null )
            {
                result = progress.getElements();
            }
        }
        catch ( JDOObjectNotFoundException e )
        {
            // do nothing
        }
        finally
        {
            pm.close();
        } 
        return result;
    }
}
